import { Table, Space, Card, Button, DatePicker, Select } from 'antd'
import { useStore } from '@/store'
import React, { useEffect, useState, useRef, useCallback } from 'react'
import { useSearchParams } from 'react-router-dom'
import { http, httpXp } from '@/utils'
import moment from 'moment'
import Factorscore from './components/Factorscore'
import * as echarts from 'echarts'
import { option } from './const'
import { yAxisNumber } from '@/utils/pro'
import './index.scss'
import axios from 'axios'

const { RangePicker } = DatePicker

const ScoreLine = () => {
    const [scoreData, setScoreData] = useState({
        list: [],
        count: 0
    })
    // 默认查询最近15天分值趋势
    const defaultTime = [moment(new Date()).add(-15, 'd'), moment(new Date())]

    const { loginStore } = useStore()
    const [paramsUrl] = useSearchParams()
    const [freqListOpt, setFreqListOpt] = useState([])
    const featureId = paramsUrl.get('featureId')
    const featureName = paramsUrl.get('featureName')
    const code = paramsUrl.get('code')
    const [params, setParams] = useState({
        featureId: featureId || '',
        startTime: defaultTime[0].format('YYYY-MM-DD HH:mm:ss'),
        endTime: defaultTime[1].format('YYYY-MM-DD HH:mm:ss'),
        pageNum: 1,
        pageSize: 20
    })
    const freqChange = (value) => {
        let freqId = selFreq.find(item => item.value === value).id
        setParams({
            ...params,
            freqId,
            freqName: value
        })
        getScoreLine({ freqId, freqName: value })
    }
    const indexChange = (value) => {
        console.log('indexChange', value)
        setParams({
            ...params,
            index: value
        })
        getScoreLine({ freqId: params.freqId, freqName: params.freqName, index: value })
    }
    const onSortChange = (pagination, filters, sorter) => {
        const orderByInfo = {}
        if (sorter.column) {
            orderByInfo[sorter.column.freqKey] = sorter.order ? sorter.order.replace('end', '') : ''
        }
        setParams({
            ...params,
            orderByInfo,
            pageSize: pagination.pageSize,
            pageNum: pagination.current
        })
    }
    const dateOnChange = (date) => {
        setParams({
            ...params,
            startTime: date[0].format('YYYY-MM-DD HH:mm:ss'),
            endTime: date[1].format('YYYY-MM-DD HH:mm:ss'),
        })
        getScoreLine({ date, freqId: params.freqId, freqName: params.freqName })
    }
    const [columns, setColumns] = useState([])
    const [legend, setLegend] = useState([])
    const [selFreq, setelFreq] = useState([])
    /** 因子打分详情 */
    const [factorModalOpen, setFactorModalOpen] = useState(false)
    const [configRow, setConfigRow] = useState({})
    const changeConfigModal = (val) => {
        setFactorModalOpen(val)
    }
    console.log(111)
    const domRef = useRef()
    const [selIndex, setSelIndex] = useState([])
    const getScoreLine = useCallback(async ({ date, freqId, freqName, index }) => {
        console.log(222, date, freqId, freqName)
        const myChart = echarts.init(domRef.current)
        myChart.showLoading()
        let startTime = date ? date[0].format('YYYY-MM-DD HH:mm:ss') : params.startTime
        let endTime = date ? date[1].format('YYYY-MM-DD HH:mm:ss') : params.endTime
        let frequency = ''
        switch (freqName) {
            case 'wd':
                frequency = '1d'
                break
            case 'wdh':
                frequency = '60m'
                break
            case 'totalScore':
                frequency = '5m'
                break
            default:
                frequency = freqName
                break
        }
        let ress = await axios.all([
            http.post('/alarm/deliversign/findScoreLineNew', {
                freqId,
                freqName,
                featureId: featureId,
                startTime,
                endTime
            }),
            httpXp.get(`/get_realtime_kline?code=${code}&start_date=${moment(startTime).format('YYYY-MM-DD')}&end_date=${moment(endTime).add(1, 'd').format('YYYY-MM-DD')}&frequency=${frequency}`),
            httpXp.get('/realtime_indicator', {
                params: {
                    code,
                    start_date: moment(startTime).format('YYYY-MM-DD'),
                    end_date: moment(endTime).add(1, 'd').format('YYYY-MM-DD'),
                    indicator: index ? index : 'DKX_MA',
                    frequency
                }
            })
        ])
        const res = ress[0]
        const { data: res1 } = ress[1]
        const { data: res2 } = ress[2]
        let xpdate = res2.datetime.map(d => moment(d * 1000).format('YYYY-MM-DD HH:mm:ss'))
        console.log('小平时间', xpdate)
        // 处理1w数据中台返回的最后一条为本周五时间问题
        if (freqName === '1w') {
            let lastKey = Object.keys(res.body).slice(-1)[0]
            let lastDate = new Date(res.body[lastKey][0].datetime).getTime() / 1000
            res1[res1.length - 1][0] = lastDate
            res2.datetime[res2.datetime.length - 1] = lastDate
        }
        let res1_map = new Map()
        let res2_map = new Map()
        let res2_key = Object.keys(res2).filter(item => item !== 'datetime')
        res1.forEach((item, index) => {
            let mapkey = item[0]
            // if (freqName === '60m' || freqName === 'wdh') mapkey = new Date(moment(mapkey * 1000).format('YYYY-MM-DD HH:00:00')).getTime() / 1000
            res1_map.set(mapkey, item)
            let obj = {}
            for (let i = 0; i < res2_key.length; i++) {
                const key = res2_key[i]
                obj[key] = res2[key][index]
            }
            res2_map.set(mapkey, obj)
        })
        // console.log(666)
        // console.log(res1_map)
        // console.log(res2_map)
        /**
         * 图标数据格式转换
         */
        const xAxisData = []
        const seriesObj = []
        const all_list_obj = []
        const all_list_obj1 = []

        for (const key in res.body) {
            const el = res.body[key][0]
            xAxisData.push(key)
            all_list_obj.push((el.score).toFixed(2) || 0)
            if (!seriesObj[0]) {
                seriesObj[0] = {
                    name: freqName,
                    type: 'line',
                    symbol: 'none',
                    data: [(el.score).toFixed(2) || 0],
                    itemStyle: {
                        color: '#E63F3F'
                    }
                }
            } else {
                seriesObj[0].data.push((el.score).toFixed(2) || 0)
            }
            let data1 = res1_map.get(new Date(key).getTime() / 1000)
            if (!seriesObj[1]) {
                seriesObj[1] = {
                    name: 'k线',
                    type: 'candlestick',
                    data: [],
                    yAxisIndex: 1
                }
            }
            if (data1) {
                let arr = [(data1[1]).toFixed(2), (data1[4]).toFixed(2), (data1[3]).toFixed(2), (data1[2]).toFixed(2)]
                all_list_obj1.push(...arr)
                seriesObj[1].data.push(arr || [])
            } else {
                seriesObj[1].data.push([])
            }

            let data2 = res2_map.get(new Date(key).getTime() / 1000)
            for (let i = 0; i < res2_key.length; i++) {
                const k = res2_key[i]
                if (!seriesObj[2 + i]) {
                    seriesObj[2 + i] = {
                        name: k,
                        type: 'line',
                        symbol: 'none',
                        data: [],
                        yAxisIndex: 1
                    }
                }
                if (data2) {
                    all_list_obj1.push((data2[k]).toFixed(2))
                    seriesObj[2 + i].data.push((data2[k]).toFixed(2) || null)
                } else {
                    seriesObj[2 + i].data.push(null)
                }
            }
        }
        // console.log('响响时间', xAxisData)

        // let maxLength = 0
        // let i = -1
        // for (const key in res.body) {
        //     xAxisData.push(key)
        //     maxLength = maxLength < res.body[key].length ? res.body[key].length : maxLength

        //     // 匹配指标数据1
        //     if (xAxisData.length && res2.datetime) {
        //         let dete1 = new Date(xAxisData[xAxisData.length - 1]).getTime() / 1000
        //         let dete2 = new Date(key).getTime() / 1000
        //         if (dete1 <= res2.datetime[0] && dete2 >= res2.datetime[0]) {
        //             i = xAxisData.length - 1
        //         }
        //     }
        // }
        // for (const key in res.body) {
        //     for (let index = 0; index < maxLength; index++) {
        //         const el = res.body[key][index]
        //         all_list_obj.push(el.score || null)
        //         if (seriesObj.filter(fitem => fitem.name === el.freqName).length) {
        //             seriesObj.filter(fitem => fitem.name === el.freqName)[0].data.push(el.score || null)
        //         } else {
        //             let _i = null
        //             switch (el.freqName) {
        //                 case '总':
        //                     _i = 0
        //                     break
        //                 case '1m':
        //                     _i = 1
        //                     break
        //                 case '5m':
        //                     _i = 2
        //                     break
        //                 case '15m':
        //                     _i = 3
        //                     break
        //                 case '60m':
        //                     _i = 4
        //                     break
        //                 case '1d':
        //                     _i = 5
        //                     break
        //                 case '1w':
        //                     _i = 6
        //                     break
        //                 case 'wd':
        //                     _i = 7
        //                     break
        //                 case 'wdh':
        //                     _i = 8
        //                     break
        //                 default:
        //                     break
        //             }
        //             seriesObj[_i] = {
        //                 name: el.freqName,
        //                 type: 'line',
        //                 data: [el.score || null],
        //                 itemStyle: {
        //                     color: '#E63F3F'
        //                 }
        //             }
        //         }
        //     }
        // }

        // // 匹配指标数据2
        // if (i === -1 && res2.datetime) {
        //     let _i = -1
        //     let date = new Date(xAxisData[0]).getTime() / 1000
        //     res2.datetime.forEach((item, i) => {
        //         if (item <= date && res2.datetime[i + 1] >= date) {
        //             _i = i
        //         }
        //     })
        //     console.log(999, _i)
        //     if (_i !== -1) {
        //         for (const key in res2) {
        //             if (Object.hasOwnProperty.call(res2, key)) {
        //                 if (key !== 'datetime') {
        //                     const el = res2[key]
        //                     seriesObj.push({
        //                         name: key,
        //                         type: 'line',
        //                         data: el,
        //                         symbol: 'none',
        //                         itemStyle: {
        //                             //   color
        //                         },
        //                         yAxisIndex: 1
        //                     })
        //                 }

        //             }
        //         }
        //     }
        // }
        // if (i !== -1 && res2.datetime) {
        //     console.log(888, i)
        //     for (const key in res2) {
        //         if (Object.hasOwnProperty.call(res2, key)) {
        //             if (key !== 'datetime') {
        //                 const el = [...new Array(i).fill(null), ...res2[key]]
        //                 seriesObj.push({
        //                     name: key,
        //                     type: 'line',
        //                     data: el,
        //                     symbol: 'none',
        //                     itemStyle: {
        //                         //   color
        //                     },
        //                     yAxisIndex: 1
        //                 })
        //             }

        //         }
        //     }
        // }


        // let kData = res1.map(item => {
        //     all_list_obj1.push(item[1], item[4], item[3], item[2])
        //     return [item[1], item[4], item[3], item[2]]
        // })
        // seriesObj.push({ name: 'k线', type: 'candlestick', data: kData, yAxisIndex: 1 })

        const yVal = yAxisNumber(all_list_obj)
        option.yAxis[0].min = yVal[0]
        option.yAxis[0].max = yVal[1]
        option.yAxis[0].interval = yVal[2]

        // const yVal1 = yAxisNumber(all_list_obj1)
        // option.yAxis[1].min = yVal1[0]
        // option.yAxis[1].max = yVal1[1]
        // option.yAxis[1].interval = yVal1[2]

        option.xAxis.data = xAxisData
        option.series = seriesObj

        console.log('options-', option)
        if (myChart) {
            myChart.hideLoading()
            myChart.setOption(option, { notMerge: true })
        }
    }, [featureId, params, code])
    useEffect(() => {
        console.log(333)
        const showModalOpen = (list) => {
            setConfigRow(list)
            setFactorModalOpen(true)
        }
        const getSelIndex = async () => {
            const { data: res_indicator } = await httpXp.get('/get_indicator')
            let list = []
            for (const key in res_indicator) {
                if (Object.hasOwnProperty.call(res_indicator, key)) {
                    const el = res_indicator[key]
                    if (el.WINDOW === '#0') {
                        list.push({
                            label: key,
                            value: key,
                            info: el
                        })
                    }
                }
            }
            setSelIndex(list)
        }
        const getFreq = async () => {
            const res = await http.post('/alarm/deliversign/getAllFreq')
            const list = res.body ? res.body.map(item => ({
                id: item.id,
                dataIndex: item.freqKey,
                freqKey: item.freqKey,
                title: item.freqName,
                sorter: true
            })) : [{ label: '暂无', value: '' }]
            console.log('周期列表-', list)
            setFreqListOpt(list)
            const _setelFreq = []
            list.forEach(e => {
                if (e.title !== '1m') {
                    _setelFreq.push({
                        id: e.id,
                        value: e.title,
                        label: e.title
                    })
                }
            })
            _setelFreq.push({ id: '', value: 'totalScore', label: '总分' })
            setelFreq(_setelFreq)
            setLegend(list.map(e => e.title))
            setColumns([
                { title: '时间', dataIndex: 'datetime' },
                { title: '总分', dataIndex: 'totalScore', freqKey: 'totalScore', sorter: true, },
                ...list,
                {
                    title: '操作',
                    render: data => {
                        return (
                            <Space size="middle">
                                <Button size="small" onClick={() => showModalOpen(data)}>查看详情</Button>
                            </Space>
                        )
                    },
                    fixed: 'right'
                }
            ])
            let freqId_5m = _setelFreq.find(item => item.value === '5m').id
            setParams({
                ...params,
                freqId: freqId_5m,
                freqName: '5m'
            })
            getScoreLine({ freqId: freqId_5m, freqName: '5m' })
        }
        const getList = async () => {
            const res = await http.post('/alarm/deliversign/findScoreByPage', {
                orderByInfo: { "datetime": "desc" },
                ...params
            })
            const list = res.body.list.map((e, i) => {
                const obj = {
                    featureId: featureId,
                    ...e,
                    id: i
                }
                return obj
            })
            setScoreData({
                list: [...list],
                count: res.body.total
            })
            console.log('分值趋势列表-', list)
        }
        if (!freqListOpt.length) {
            getFreq()
        }
        if (freqListOpt.length) {
            getList()
        }
        if (!selIndex.length) {
            getSelIndex()
        }
    }, [params, legend, loginStore, freqListOpt, featureId, columns, getScoreLine, selIndex])

    return (
        <>
            <Card
                // title={`分值趋势 （${featureName}）`}
                title={'分值趋势'}
                style={{ boxSizing: 'border-box' }}
            // extra={<RangePicker
            //     format="YYYY-MM-DD HH:mm"
            //     showTime={{
            //         format: 'HH:mm',
            //     }}
            //     defaultValue={defaultTime}
            //     onChange={dateOnChange}
            // />}
            >
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Space style={{ minWidth: 160 }}>
                        <h3>{featureName}</h3>
                        <Select
                            defaultValue="5m"
                            style={{ width: 215 }}
                            onChange={freqChange}
                            options={selFreq}
                        />
                        <Select
                            defaultValue="DKX_MA"
                            style={{ width: 215 }}
                            onChange={indexChange}
                            options={selIndex}
                        />
                    </Space>

                    <RangePicker
                        format="YYYY-MM-DD HH:mm"
                        showTime={{
                            format: 'HH:mm',
                        }}
                        defaultValue={defaultTime}
                        onChange={dateOnChange}
                    />
                </div>
                <div className='echart' ref={domRef} style={{ height: '400px', }}></div>
                <Table
                    style={{ marginTop: 20 }}
                    rowKey="id"
                    size='middle'
                    columns={columns}
                    dataSource={scoreData.list}
                    onChange={onSortChange}
                    pagination={
                        {
                            size: 'default',
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSize: params.pageSize,
                            total: scoreData.count,
                            current: params.pageNum,
                            showTotal: (total, range) => `共 ${total} 条`,
                        }
                    }
                    bordered
                />
            </Card >
            <Factorscore configRow={configRow} factorModalOpen={factorModalOpen} changeConfigModal={changeConfigModal}></Factorscore>
        </>
    )
}

export default ScoreLine